package com.leeh.jsontest;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static com.leeh.jsontest.Constents.URL_OURSELVES_COURSE_COURSE;
import static com.leeh.jsontest.Constents.URL_OURSELVES_COURSE_LIST;
import static com.leeh.jsontest.Constents.URL_OURSELVES_COURSE_VALIDATE;
import static com.leeh.jsontest.Constents.URL_OURSELVES_TERM_LIST;

/**
 * Created by Liheng on 2017-04-16.
 */

public class CourseFragment extends Fragment {

    private Handler handler;
    private ImageView imgVerCode;
    private EditText txtVerCode;
    private TextView txtNetwork;
    private Spinner spCourse;
    private Spinner spTerm;
    private Button btnSearch;
    private LinearLayout verCodeLinearLayout;
    private CourseViewOne courseViewOne;
    private ProgressBar pbLoading;

    private SpinnerAdapter courseAdapter = null;
    private List<SpinnerContent> courseList = null;

    private SpinnerAdapter termAdapter = null;
    private List<SpinnerContent> termList = null;

    private MySqliteHelper helper;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_course, container, false);

        AsynchronousTask();
        initView(view);
        initData();
        initEvents();

        return view;
    }


    /**
     * 更新UI
     */
    public void AsynchronousTask() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case Constents.GET_VERCODER: {
                        pbLoading.setVisibility(View.GONE);
                        byte[] imageByte = msg.getData().getByteArray("verCode");
                        Bitmap image = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
                        imgVerCode.setImageBitmap(image);
                        break;
                    }
                    case Constents.GET_COURSE: {
                        handleGetCourseInfo((String) msg.obj);
                        break;
                    }
                    case Constents.GET_SPINNER_CONTENT: {
                        handleSpinnerContent((String) msg.obj, msg.arg1);
                        break;
                    }
                    case Constents.GET_DISABLE_NETWORK: {
                        txtNetwork.setVisibility(View.VISIBLE);
                        break;
                    }

                }
            }
        };
    }

    /**
     * 处理获取到的课表信息
     *
     * @param html
     */
    private void handleGetCourseInfo(String html) {
        if (DataParse.parseCheckVerCode(html)) {
            List<String> courseData = DataParse.parseCourse(html);
            StringBuilder course = new StringBuilder();
            if (courseData.size() == 0) {
                course.append("没有课程");
            } else {
                String termKey = termList.get(spTerm.getSelectedItemPosition()).getKey();
                String courseKey = courseList.get(spCourse.getSelectedItemPosition()).getKey();
                String courseValue = courseList.get(spCourse.getSelectedItemPosition()).getValue();
                DBManager.insertIntoCourseTable(helper.openDatabase(), termKey, courseKey, courseValue, "1", html);
            }
            courseViewOne.setData(courseData);
            //txtCourse.setText(course.toString());
            courseViewOne.setVisibility(View.VISIBLE);
            verCodeLinearLayout.setVisibility(View.GONE);
            pbLoading.setVisibility(View.GONE);
        } else {
            if (verCodeLinearLayout.getVisibility() == View.VISIBLE) {
                Toast.makeText(getActivity(), "验证码输入错误!", Toast.LENGTH_LONG).show();
            }
            DataUtils.getVerCode(handler, URL_OURSELVES_COURSE_VALIDATE);
            verCodeLinearLayout.setVisibility(View.VISIBLE);
            pbLoading.setVisibility(View.VISIBLE);
            courseViewOne.setVisibility(View.GONE);
            txtVerCode.setText("");
        }
    }

    /**
     * 处理下拉框内容
     *
     * @param html
     */
    private void handleSpinnerContent(String html, int type) {
        switch (type) {
            case 40: {
                courseList = DataParse.parseSpinnerFromJsonToList(html, "course");
                courseAdapter.addAll(courseList);
                DBManager.setCourseSpinner(helper.openDatabase(), courseList);
                //Log.i("teacher", "handleSpinnerContent: " + teacherList.size());
                break;
            }
            case 41: {
                termList = DataParse.parseSpinnerFromJsonToList(html, "term");
                termAdapter.addAll(termList);
                DBManager.insertIntoTerm(helper.openDatabase(), termList);
                Log.i("term", "handleSpinnerContent: " + termList.size());
                break;
            }
        }

    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        imgVerCode = (ImageView) view.findViewById(R.id.verCode_image);
        txtVerCode = (EditText) view.findViewById(R.id.verCode_text);
        txtNetwork = (TextView) view.findViewById(R.id.network_connection_textView);
        courseViewOne = (CourseViewOne) view.findViewById(R.id.course_table_courseView);
        spCourse = (Spinner) view.findViewById(R.id.course_spinner);
        spTerm = (Spinner) view.findViewById(R.id.term_spinner);
        btnSearch = (Button) view.findViewById(R.id.search_button);
        verCodeLinearLayout = (LinearLayout) view.findViewById(R.id.verCode_linearLayout);
        pbLoading = (ProgressBar) view.findViewById(R.id.loading_progressBar);
    }

    /**
     * 初始化事件
     */
    private void initEvents() {
        imgVerCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataUtils.getVerCode(handler, URL_OURSELVES_COURSE_VALIDATE);
            }
        });

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtNetwork.setVisibility(View.GONE);
                if (spCourse.getSelectedItemPosition() == -1 || courseList.get(spCourse.getSelectedItemPosition()).getKey().equals("")) {
                    Toast.makeText(getActivity(), "请选择课程!", Toast.LENGTH_LONG).show();
                } else {
                    boolean isExist = searchFromDatabaseCourse();
                    if (!isExist) {
                        //verCodeLinearLayout.setVisibility(View.GONE);
                        courseViewOne.setVisibility(View.GONE);
                        pbLoading.setVisibility(View.VISIBLE);
                        Map<String, String> dataParams = new HashMap<String, String>();
                        dataParams.put("Sel_XNXQ", termList.get(spTerm.getSelectedItemPosition()).getKey());
                        dataParams.put("Sel_KC", courseList.get(spCourse.getSelectedItemPosition()).getKey());
                        dataParams.put("type", "1");
                        dataParams.put("txt_yzm", txtVerCode.getText().toString().trim());

                        DataUtils.searchFromNetworkCourse(handler, URL_OURSELVES_COURSE_COURSE, dataParams);
                        txtVerCode.setText("");
                    }
                    //软盘消失
                    InputMethodManager imm = ((InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE));
                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
                    imm.hideSoftInputFromWindow(txtVerCode.getWindowToken(), 0);
                }
            }
        });

        txtNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (android.os.Build.VERSION.SDK_INT > 13) {
                        startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
                    } else {
                        startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        courseViewOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = ((AppCompatTextView) view).getText().toString();
                if (content.equals("")) {
                    content = "没课哦，可以自由安排了！";
                }
                CourseDetailDialog dialog = new CourseDetailDialog(getActivity());
                dialog.showDialog(content, R.layout.dialog_course_detail, 60, 120);
            }
        });

    }

    /**
     * 初始化数据
     */
    private void initData() {
        helper = MySqliteHelper.getInstance(getActivity());

        termList = DBManager.getTermSpinnerContent(helper.openDatabase());
        if (termList.size() == 0) {
            DataUtils.getOptionInfoFromNetWork(handler, URL_OURSELVES_TERM_LIST, 41);
        }
        courseList = DBManager.getCourseSpinner(helper.openDatabase());
        if (courseList.size() == 0) {
            DataUtils.getOptionInfoFromNetWork(handler, URL_OURSELVES_COURSE_LIST, 40);
        }

        courseAdapter = new SpinnerAdapter(getActivity(), R.layout.spinner_content, courseList);
        courseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCourse.setAdapter(courseAdapter);

        termAdapter = new SpinnerAdapter(getActivity(), R.layout.spinner_content, termList);
        termAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spTerm.setAdapter(termAdapter);
    }

    /**
     * 从数据库去数据
     */
    public boolean searchFromDatabaseCourse() {
        String termKey = termList.get(spTerm.getSelectedItemPosition()).getKey();
        String teacherKey = courseList.get(spCourse.getSelectedItemPosition()).getKey();
        String teacherValue = courseList.get(spCourse.getSelectedItemPosition()).getValue();
        String html = DBManager.teacherCourseQuery(helper.openDatabase(), termKey, teacherKey, teacherValue, "1");
        if (html.equals("")) {
            return false;
        }
        List<String> courseData = DataParse.parseCourse(html);
        StringBuilder course = new StringBuilder();
        for (String str : courseData) {
            course.append(str + "\n");
        }
        Log.i("lllllll", "searchFromDatabaseCourse: " + courseData.size());
        courseViewOne.setData(courseData);
        courseViewOne.setVisibility(View.VISIBLE);
        //txtCourse.setText(course.toString());
        return true;
    }

}
